package de.recipeminer.tools;

import com.google.common.base.Joiner;
import org.jruby.embed.ScriptingContainer;

import java.io.File;
import java.io.IOException;

public class RubyRunner {
    public static void main(String[] args) {
        File scriptFile = null;
        try {
            scriptFile = new File(args[0]);
            if (!scriptFile.isAbsolute()) {
                //String basePath = args[0].matches(".*(T|t)est.*") ? Tools.getRubyTestSourcePath()
                //                                              : Tools.getRubyTestSourcePath();
                String basePath = Tools.getRubySourcePath();
                String expandedPath = Joiner.on(File.separator).join(basePath, scriptFile);
                scriptFile = new File(expandedPath);
            }
            if(!scriptFile.exists()) {
                String message = String.format("Script file does not exist: '%s'", scriptFile);
                throw new IOException(message);
            }

        } catch (Exception e) {
            throw new IllegalArgumentException("Invalid script file given:", e);
        }
        ScriptingContainer container = RubyScriptContainerProvider.getDefaultContainer();
        container.put("script", scriptFile.getAbsolutePath());
        container.runScriptlet("puts \"running: #{script}\"");
        container.runScriptlet("require(script)");
    }
}
